<script setup>
import { defineEmits, defineProps, ref } from 'vue'

const props = defineProps({
  item: { type: Object, required: true },
})

const emit = defineEmits(['toggle', 'delete', 'update'])

const isEditing = ref(false)
const editingText = ref('')

function startEdit() {
  isEditing.value = true
  editingText.value = props.item.text
}
function confirmEdit() {
  const t = editingText.value.trim()
  if (!t) emit('delete', props.item.id)
  else emit('update', { id: props.item.id, text: t })
  isEditing.value = false
}
function cancelEdit() {
  isEditing.value = false
}
</script>

<template>
  <li :class="{ done: item.completed }" class="row">
    <input type="checkbox" :checked="item.completed" @change="emit('toggle', item.id)" />

    <span v-if="!isEditing" class="text" @dblclick="startEdit">{{ item.text }}</span>
    <input
      v-else
      class="edit-input"
      v-model="editingText"
      @keyup.enter="confirmEdit"
      @keyup.esc="cancelEdit"
      @blur="confirmEdit"
      autofocus
    />

    <button class="del" @click="emit('delete', item.id)">删除</button>
  </li>
</template>

<style scoped>
.row { display: grid; grid-template-columns: 24px 1fr auto; align-items: center; gap: 10px; padding: 10px 0; border-bottom: 1px dashed #eee; }
.done .text { text-decoration: line-through; color: #999; }
.text { user-select: none; }
.edit-input { width: 100%; height: 32px; padding: 0 10px; border: 1px solid #ddd; border-radius: 6px; }
.del { color: #ff4d4f; border: 1px solid #ffd1d2; padding: 4px 10px; background: #fff5f5; border-radius: 6px; cursor: pointer; }
</style>


